import router from './router'
import { asynRouterMap, constantRouterMap } from './router'
import NProgress, { set } from 'nprogress'
import 'nprogress/nprogress.css'
import store from './store'
import getPageTitle from '@/utils/get-page-title'

NProgress.configure({
  showSpinner: false
})

const whiteList = ['/login'] // 不重定向白名单
router.beforeEach(async(to, from, next) => {
  NProgress.start()
  document.title = getPageTitle(to.meta.title)
  if (to.query.token) {
    store.dispatch('Token', to.query.token)
    setTimeout(function(){
      setRoutes();
      next();
      NProgress.done();
    }, 800);
    return
  }
  if (store.getters.token) {
    if (to.path === '/login') {
      next({
        path: '/'
      })
      NProgress.done()
    } else {
      // if (store.getters.roles.length === 0) {
      //   store.dispatch('GetInfo').then(res => { // 拉取用户信息
      //     next()
      //   }).catch((err) => {
      //     store.dispatch('FedLogOut').then(() => {
      //       Message.error(err || 'Verification failed, please login again')
      //       next({ path: '/' })
      //     })
      //   })
      // } else {
      //   next()
      // }
      setRoutes()
      next()
    }
  } else {
    if (whiteList.indexOf(to.path) !== -1) {
      next()
    } else {
      next(`/login?redirect=${to.path}`) // 否则全部重定向到登录页
      NProgress.done()
    }
  }
})

function setRoutes(){
  if (store.getters.role) {
    var routes;
    if (store.getters.role === 1) {
      var routesAdd = constantRouterMap.concat();
      routesAdd.push(asynRouterMap[2]);
      routesAdd.push(asynRouterMap[1]);
      routesAdd.push(asynRouterMap[0]);
      routes = routesAdd;
    } else {
      routes = constantRouterMap;
    }
    router.options.routes = routes;
    router.addRoutes(routes);
  }
}

router.afterEach(() => {
  NProgress.done() // 结束Progress
})
